import React, { CSSProperties } from 'react'
import { Lock } from '@material-ui/icons'
import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, TextField, Button } from '@material-ui/core'
import Message from '../../../components/Message/Message'
import { CgAns,chPwd } from '../../../api/user'

const ChangePwdStyle: CSSProperties = {
    backgroundColor: '#fff',
    boxShadow: '1px 2px 25px 0px rgb(0 0 0 / 10%)',
    borderRadius: '15px',
    margin: '2vh 4vw',
    padding: '1.5vh 3vw',
    display: 'flex',
    alignItems: 'center'
}
const ChangePwd = () => {
    const pwdReg = /^[a-z0-9_-]{6,18}$/
    const [open,setOpen] = React.useState<boolean>(false)
    const [oldPwd,setOld] = React.useState<string>('')
    const [newPwd,setNew] = React.useState<string>('')
    const handleUpdate = () => {
        if(pwdReg.test(oldPwd) && pwdReg.test(newPwd)){
            chPwd(oldPwd,newPwd)
                .then(res => {
                    const {code,msg} = res as unknown as CgAns
                    setOld('')
                    setNew('')
                    if(code === 200){
                        setOpen(false)
                        Message('success',`${msg}，新密码将在下次登录时生效`)
                    }else{
                        Message('error',msg)
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        }else{
            setOld('')
            setNew('')
            Message('error','密码格式不正确')
        }
    }
    return (
        <>
            <div style={ChangePwdStyle} onClick={() => {setOpen(true)}}>
                <Lock />
                <span style={{ marginLeft: '4vw', fontSize: '13px' }}>修改密码</span>
            </div>
            <Dialog open={open}>
            <DialogTitle>修改密码</DialogTitle>
                <DialogContent>
                    <DialogContentText>
                        请分别填写您的新旧密码：6-18位英文字符或数字组合
                    </DialogContentText>
                    <TextField  autoFocus id="oldPwd" label="旧密码" type="password"  fullWidth variant="standard" value={oldPwd} color='secondary' onChange={(e) => {
                        setOld(e.target.value)
                    }}/>
                    <TextField  id="newPwd" label="新密码" type="password"  fullWidth variant="standard" value={newPwd} color='secondary' onChange={(e) => {
                        setNew(e.target.value)
                    }}/>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleUpdate} color='secondary'>更改</Button>
                    <Button onClick={() => {setOpen(false)}} color='secondary'>取消</Button>
                </DialogActions>
            </Dialog>
        </>
    )
}

export default ChangePwd